package com.yuan.websocket.handler;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.yuan.utils.WebSocketUtils;
import com.yuan.websocket.dto.WebSocketMessageDto;
import com.yuan.websocket.holder.WebSocketSessionHolder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.socket.*;
import org.springframework.web.socket.client.standard.StandardWebSocketClient;
import org.springframework.web.socket.handler.AbstractWebSocketHandler;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;

@Slf4j
public class PlusWebSocketHandler extends AbstractWebSocketHandler {

    /**
     * 连接成功后
     */
    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws IOException {

        String deviceId = null;
        try {
            deviceId = session.getUri().getQuery().split("deviceId=")[1];
        } catch (Exception e) {
            log.error("获取 deviceId 失败", e);
            return;
        }
        //String deviceId = session.getAttributes().get("deviceId").toString();
        WebSocketSessionHolder.addSession(deviceId, session);
        log.info("[connect] sessionId: {},deviceId:{}", session.getId(), deviceId);
    }

    /**
     * 处理接收到的文本消息
     *
     * @param session WebSocket会话
     * @param message 接收到的文本消息
     * @throws Exception 处理消息过程中可能抛出的异常
     */
    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        // 从WebSocket会话中获取登录用户信息
        String deviceId = session.getAttributes().get("deviceId").toString();
        // 创建WebSocket消息DTO对象
        WebSocketMessageDto webSocketMessageDto = new WebSocketMessageDto();
        webSocketMessageDto.setSessionKeys(List.of(deviceId));
        webSocketMessageDto.setMessage(message.getPayload());
        WebSocketUtils.publishMessage(webSocketMessageDto);
    }

    private final String socketWbUrl = "wss://dashscope.aliyuncs.com/api-ws/v1/inference";

    /**
     * 处理接收到的二进制消息
     *
     * @param session WebSocket会话
     * @param message 接收到的二进制消息
     * @throws Exception 处理消息过程中可能抛出的异常
     */
    @Override
    protected void handleBinaryMessage(WebSocketSession session, BinaryMessage message) throws Exception {
        log.info("接收到二进制消息，大小: {}", message.getPayloadLength());
        String deviceId = null;
        try {
            deviceId = session.getUri().getQuery().split("deviceId=")[1];
        } catch (Exception e) {
            log.error("获取 deviceId 失败", e);
            return;
        }
        
        // 前端传过来的音频数据
        ByteBuffer pcmData = message.getPayload();
        // 连接到目标 WebSocket 服务
        StandardWebSocketClient client = new StandardWebSocketClient();
        WebSocketHttpHeaders headers = new WebSocketHttpHeaders();
        headers.add("Authorization", "bearer "  );
        //"user-agent": "your_platform_info", //可选
        //"X-DashScope-WorkSpace": workspace, // 可选
        headers.add("X-DashScope-DataInspection", "enable");


        CompletableFuture<WebSocketSession> sessionFuture = client.execute(new AbstractWebSocketHandler() {
            @Override
            public void afterConnectionEstablished(WebSocketSession innerSession) throws Exception {
                // 发送启动语音识别指令


                // 发送 PCM 数据
                innerSession.sendMessage(new BinaryMessage(pcmData));
                log.info("PCM 数据已发送到目标服务");
            }

            @Override
            protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
                // 接收识别结果
                String recognitionResult = message.getPayload();
                log.info("接收到识别结果: {}", recognitionResult);

                // 解析识别结果
                ObjectMapper objectMapper = new ObjectMapper();
                Map<String, Object> resultMap = objectMapper.readValue(recognitionResult, Map.class);

                // 处理识别结果
                String recognizedText = (String) resultMap.get("text");
                log.info("识别后的文本: {}", recognizedText);
            }

            @Override
            public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
                log.error("WebSocket 传输错误: {}", exception.getMessage(), exception);
            }

            @Override
            public void afterConnectionClosed(WebSocketSession session, CloseStatus closeStatus) throws Exception {
                log.info("WebSocket 连接已关闭: {}", closeStatus);
            }
        }, socketWbUrl,headers);

        // 等待连接完成
        WebSocketSession webSocketSession = sessionFuture.get();
        // 确保连接在使用完毕后关闭
        Runtime.getRuntime().addShutdownHook(new Thread(() -> {
            try {
                if (webSocketSession != null && webSocketSession.isOpen()) {
                    webSocketSession.close();
                }
            } catch (IOException e) {
                log.error("关闭 WebSocket 连接时发生错误: {}", e.getMessage(), e);
            }
        }));



        //super.handleBinaryMessage(session, message);
    }

    /**
     * 处理接收到的Pong消息（心跳监测）
     *
     * @param session WebSocket会话
     * @param message 接收到的Pong消息
     * @throws Exception 处理消息过程中可能抛出的异常
     */
    @Override
    protected void handlePongMessage(WebSocketSession session, PongMessage message) throws Exception {
        WebSocketUtils.sendPongMessage(session);
    }

    /**
     * 处理WebSocket传输错误
     *
     * @param session   WebSocket会话
     * @param exception 发生的异常
     * @throws Exception 处理过程中可能抛出的异常
     */
    @Override
    public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
        log.error("[transport error] sessionId: {} , exception:{}", session.getId(), exception.getMessage());
    }

    /**
     * 在WebSocket连接关闭后执行清理操作
     *
     * @param session WebSocket会话
     * @param status  关闭状态信息
     */
    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) {
        //String deviceId = session.getAttributes().get("deviceId").toString();
        String deviceId = null;
        try {
            deviceId = session.getUri().getQuery().split("deviceId=")[1];
        } catch (Exception e) {
            log.error("获取 deviceId 失败", e);
            return;
        }
        WebSocketSessionHolder.removeSession(deviceId);
        log.info("[disconnect] sessionId: {},deviceId:{}", session.getId(), deviceId);
    }

    /**
     * 指示处理程序是否支持接收部分消息
     *
     * @return 如果支持接收部分消息，则返回true；否则返回false
     */
    @Override
    public boolean supportsPartialMessages() {
        return false;
    }
}
